//JavaScript Framework 2.0 Code
try {
	Type.registerNamespace('com.yonyou.ncmm_pac_pda.OutForSOScanListController');
	com.yonyou.ncmm_pac_pda.OutForSOScanListController = function() {
		com.yonyou.ncmm_pac_pda.OutForSOScanListController.initializeBase(this);
		this.initialize();
	}

	function com$yonyou$ncmm_pac_pda$OutForSOScanListController$initialize() {
		//you can programing by $ctx API
		//get the context data through $ctx.get()
		//set the context data through $ctx.push(json)
		//set the field of the context through $ctx.put(fieldName, fieldValue)
		//get the parameter of the context through $ctx.param(parameterName)
		//Demo Code:
		//    var str = $ctx.getString();      //获取当前Context对应的字符串
		//    alert($ctx.getString())          //alert当前Context对应的字符串
		//    var json = $ctx.getJSONObject(); //获取当前Context，返回值为json
		//    json["x"] = "a";        //为当前json增加字段
		//    json["y"] = [];           //为当前json增加数组
		//    $ctx.push(json);            //设置context，并自动调用数据绑定
		//    
		//    put方法需手动调用databind()
		//    var x = $ctx.get("x");    //获取x字段值
		//    $ctx.put("x", "b");     //设置x字段值
		//    $ctx.put("x", "b");     //设置x字段值
		//    $ctx.databind();            //调用数据绑定才能将修改的字段绑定到控件上
		//    var p1 = $param.getString("p1");   //获取参数p2的值，返回一个字符串
		//    var p2 = $param.getJSONObject("p2");   //获取参数p3的值，返回一个JSON对象
		//    var p3 = $param.getJSONArray("p3");   //获取参数p1的值，返回一个数组

		//your initialize code below...

	}

	function com$yonyou$ncmm_pac_pda$OutForSOScanListController$evaljs(js) {
		eval(js)
	}
	//加载扫描记录
	function com$yonyou$ncmm_pac_pda$OutForSOScanListController$loadScanList(sender, args) {
		// 加载数据的时候判断如果有表则查询，如果不存在数据表则先创建
		NCMMPubUtil.createTable(DeliveryScanVO);
	    loadDeliveryScanListData();
				
	}
function com$yonyou$ncmm_pac_pda$OutForSOScanListController$showDetail(sender, args) {
		$view.closePop(popDialogInfo);
		var row = $id("soutscanlistview").get("row");
		//row = $stringToJSON(row);
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.OutForSOScanDetail", //目标页面（首字母大写）全名
			"isKeep": "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
			"row": row
		});
	}

	function com$yonyou$ncmm_pac_pda$OutForSOScanListController$itemDelete(sender, args) {
		$view.closePop(popDialogInfo);
		var params = {
			"title": "提示",
			"message": "确定删除所选记录吗？",
			"okbuttontitle": "确定",
			"cancelbuttontitle": "取消",
			"style": "ok-cancel",
			"okaction": "doDelete()",
			"cancelaction": "doCancel()"
		};
		$view.openDialog(params);
	}

	function doCancel() {
		$toast("删除操作已取消。");
	}

	//执行清除操作
	function doDelete() {
		var row = $id("soutscanlistview").get("row");
		row = $stringToJSON(row);
		NCMMPubUtil.deleteVO(DeliveryScanVO, row);
		//更新发货单入库列表增加扫描数量 
		DeliveryUtil.updateDeliveryScanedNum(row.cdeliverybid);		
		$toast("删除成功。");
		loadDeliveryScanListData();
	}

	function getSubScanedNum(scanedNum, currentScanedNum) {
		if(scanedNum == null || scanedNum == "") {
			scanedNum += "00.00000";
		} else {
			scanedNum = parseFloat(scanedNum);
		}
		if(currentScanedNum == null || currentScanedNum == "") {
			currentScanedNum += "1.00000";
		} else {
			currentScanedNum = parseFloat(currentScanedNum);
		}
		var newScanedNum = parseFloat(scanedNum).sub(parseFloat(currentScanedNum));
		return newScanedNum;
	}
	function getQueryRowSql() {
        var sql = "SELECT " +
            DeliveryScanVO.VBILLCODE.name + ", " + DeliveryScanVO.CROWNO.name + ", " +
            DeliveryScanVO.CMATERIALVID_NAME.name + ", " + DeliveryScanVO.NSCANNUM.name +
            " FROM " + DeliveryScanVO.prototype.getTableName() +
            " group by " + DeliveryScanVO.VBILLCODE.name + ", " + DeliveryScanVO.CROWNO.name;
        
        return sql;
    }
    function getOutScanVOsBySql(data){
        var rtn=new Array();
        var bitnumberJson={};
        Array.prototype.map.call(data, function(vo) {
            var vbillcode = vo[DeliveryScanVO.VBILLCODE.name];
            var crowno = vo[DeliveryScanVO.CROWNO.name];
            var wheresql = "where " + DeliveryScanVO.VBILLCODE.name + "='" + vbillcode + "' and " + DeliveryScanVO.CROWNO.name + "='" + crowno + "' ";
            var sum = 0;
            var cunitid="";
            NCMMPubUtil.queryVO(DeliveryScanVO, wheresql, function(subdata) {
               var showData= eval(subdata);
               showData = NCMMPubUtil.htmlspecialjsonarray2UI(showData);
                if(NCMMPubUtil.isNotEmpty(showData)) {
                    for(var i = 0; i < showData.length; i++) {
                    var itemData = showData[i];
                    if(NCMMPubUtil.isEmpty(bitnumberJson) || NCMMPubUtil.isEmpty(bitnumberJson[itemData["cunitid"]])) {
                    var bitnumber = DeliveryUtil.getUnitBitnumber(itemData["cunitid"]);
                    if(!NCMMPubUtil.isEmpty(bitnumber)) {
                        bitnumberJson[itemData["cunitid"]] = bitnumber;
                    }
                }
                if(NCMMPubUtil.isEmpty(bitnumberJson) || NCMMPubUtil.isEmpty(bitnumberJson[itemData["castunitid"]])) {
                    var bitnumber = DeliveryUtil.getUnitBitnumber(itemData["castunitid"]);
                    if(!NCMMPubUtil.isEmpty(bitnumber)) {
                        bitnumberJson[itemData["castunitid"]] = bitnumber;
                    }
                }
                if(!NCMMPubUtil.isEmpty(bitnumberJson) && !NCMMPubUtil.isEmpty(bitnumberJson[itemData["cunitid"]])) {

                    showData[i]["nnum"] = parseFloat(showData[i]["nnum"]).toFixed(bitnumberJson[itemData["cunitid"]]);
                    showData[i]["nscannum"] = parseFloat(showData[i]["nscannum"]).toFixed(bitnumberJson[itemData["cunitid"]]);
                }
                if(!NCMMPubUtil.isEmpty(bitnumberJson) && !NCMMPubUtil.isEmpty(bitnumberJson[itemData["castunitid"]])) {
                    showData[i]["nastnum"] = parseFloat(showData[i]["nastnum"]).toFixed(bitnumberJson[itemData["castunitid"]]);
                    showData[i]["nscanastnum"] = parseFloat(showData[i]["nscanastnum"]).toFixed(bitnumberJson[itemData["castunitid"]]);
                }
              
                 var scanednum = itemData[DeliveryScanVO.NSCANNUM.name];
                 //$alert("sum=" + sum.toString() + " scanednum=" + scanednum);
                 sum = DeliveryUtil.getAddNum(sum, scanednum);

                 }  
                   cunitid=showData[0]["cunitid"];                 
                }
                vo["row"] = showData;
                if(NCMMPubUtil.isEmpty(bitnumberJson) || NCMMPubUtil.isEmpty(bitnumberJson[itemData["castunitid"]])) {
                    var bitnumber = DeliveryUtil.getUnitBitnumber(cunitid);
                    if(!NCMMPubUtil.isEmpty(bitnumber)) {
                        bitnumberJson[cunitid] = bitnumber;
                    }
                }
                if(!NCMMPubUtil.isEmpty(bitnumberJson) && !NCMMPubUtil.isEmpty(bitnumberJson[cunitid])) {
                    sum = parseFloat(sum).toFixed(bitnumberJson[cunitid]);                  
                }
                vo["sumScanedNum"] = sum;
                rtn.push(vo);
            });
        });     
        return rtn;
    }
	//加载到货单扫描记录
	function loadDeliveryScanListData() {
	   //按照订单号和行号分组查询
	   var sql = getQueryRowSql();
	   var data = NCMMPubUtil.queryBySQL(sql);
       data=eval(data);
       data = NCMMPubUtil.htmlspecialjsonarray2UI(data);
       var scangroups = getOutScanVOsBySql(data);
       //$alert("scangroups="+$jsonToString({scangroups:scangroups}));
        //显示
        $ctx.push({
            scanlist: scangroups
        });			
	}
	//全选
	function com$yonyou$ncmm_pac_pda$OutForSOScanListController$doAllChecked(sender, args) {
		$ctx.dataCollect();
		var isChecked = $id(sender).get("checked");
		var sourceData = $ctx.getJSONArray("scanlist");
		for(var i = 0; i < sourceData.length; i++) {
			sourceData[i]["isChecked"] = isChecked;
            for(var j = 0; j < (sourceData[i]["row"]).length; j++) {
                ((sourceData[i]["row"])[j])["ischecked"] = isChecked;
            }
		}

		var json = {};
		json["scanlist"] = sourceData;
		json["isAllChecked"] = isChecked;
		$ctx.push(json); //将数据显示在控件上
	}
	//选中
	function com$yonyou$ncmm_pac_pda$OutForSOScanListController$doChecked(sender, args) {
		var isCheckedAll = true;
		$ctx.dataCollect();
		var sourceData = $ctx.getJSONArray("scanlist");
		for(var i = 0; i < sourceData.length; i++) {
			if(sourceData[i]["isChecked"] == null || sourceData[i]["isChecked"] == false || sourceData[i]["isChecked"] == "false") {
				isCheckedAll = false;
                for(var j = 0; j < (sourceData[i]["row"]).length; j++) {
                    ((sourceData[i]["row"])[j])["ischecked"] = false;
                }
             } else {
                for(var j = 0; j < (sourceData[i]["row"]).length; j++) {
                    ((sourceData[i]["row"])[j])["ischecked"] = true;
                }
			}
		}
		$ctx.put("scanlist",sourceData);
		$ctx.put("isAllChecked", isCheckedAll); //更新全选复选框的界面显示
		$ctx.dataBind();
	}
	//提交
	function com$yonyou$ncmm_pac_pda$OutForSOScanListController$doCommit(sender, args) {
		var stordoc = $cache.read("defaultstordoc");		
		//连接验证成功后的后续处理
		$js.showLoadingBar();
		$ctx.dataCollect();
		var sourceData = $ctx.getJSONArray("scanlist");
		var scanCount={};
		var scanNum={};
		var itemPKs=[];
		var headJson = {};
		var itemJson = {};
		var bbitemJson = {};
		var itemKeyJson = {};
		var needCommit = false;
		var hidAndNScanNum = {};
		var headKey = [];
		for(var i = 0; i < sourceData.length; i++) {
			//过滤出需要下载的档案
			if(sourceData[i]["isChecked"] != null && (sourceData[i]["isChecked"] == true || sourceData[i]["isChecked"] == "true")) {
				needCommit = true;
				
				for(var j=0;j<sourceData[i]["row"].length;j++){
				var json = sourceData[i]["row"][j];
				var stordocid;
				if(stordoc == null || stordoc == "") {
				   if(NCMMPubUtil.isEmpty(json.csendstordocid)){	
				   $js.hideLoadingBar();			   
			           $alert("默认仓库不能为空，请设置！");
			           return;
			       }
			       else{
			       stordocid=json.csendstordocid;
			       }
		        }
		        else{
		          stordocid=$stringToJSON(stordoc).pk_stordoc;
		        }
		        if(NCMMPubUtil.isEmpty(stordocid)){		
		        $js.hideLoadingBar();		   
			       $alert("默认仓库不能为空，请设置！");
			       return;
			     }
				var itemKey = json.cdeliverybid + json.vbatchcode;
				itemPKs.push(json.cdeliverybid);
				//增加扫描记录数
				if(NCMMPubUtil.isEmpty(scanCount[json.cdeliverybid])){
				   scanCount[json.cdeliverybid]=1;
				}
				else{
				   scanCount[json.cdeliverybid]=scanCount[json.cdeliverybid]+1;
				}
				//增加扫描累计
				if(NCMMPubUtil.isEmpty(scanNum[json.cdeliverybid])){
				   scanNum[json.cdeliverybid]=json.nscannum;
				}
				else{
				   scanNum[json.cdeliverybid]=getAddScanedNum(scanNum[json.cdeliverybid], json.nscannum);					
				}
				//处理头map
				if(NCMMPubUtil.isEmpty(headJson) || NCMMPubUtil.isEmpty(headJson[json.cdeliveryid+stordocid])) {
					var head = {};
					head["csourcebillhid"] = json.cdeliveryid;
					head["cwarehouseid"] = stordocid;
					head["ts_h"] = json.hts;
					headJson[json.cdeliveryid+stordocid] = head;
					headKey.push(json.cdeliveryid+stordocid);
					itemKeyJson[json.cdeliveryid+stordocid] = [];
				}
				//处理体Map			
				if(NCMMPubUtil.isEmpty(itemJson) || NCMMPubUtil.isEmpty(itemJson[itemKey])) {
					var item = {};
					item["csourcebillbid"] = json.cdeliverybid;
					item["cmaterialvid"] = json.cmaterialvid;
					item["castunitid"] = json.castunitid;
					item["pk_batchcode"] = json.pk_batchcode;
					item["vbatchcode"] = json.vbatchcode;
					item["nscannum"] = json.nscannum;
					item["nscanastnum"] = json.nscanastnum;
					item["ts_b"] = json.bts;
					item["vnotebody"]=json.vnotebody;
					itemJson[itemKey] = item;
					var newItemKey = itemKeyJson[json.cdeliveryid+stordocid];
					newItemKey.push(itemKey);
					itemKeyJson[json.cdeliveryid+stordocid] = newItemKey;
				} else {
					var newItem = itemJson[itemKey];
					newItem.nscannum = getAddScanedNum(newItem.nscannum, json.nscannum);
					itemJson[itemKey] = newItem;
				}
				if (NCMMPubUtil.isNotEmpty(hidAndNScanNum) && NCMMPubUtil.isNotEmpty(hidAndNScanNum[json.csourcebillbid])) {
					var nScanedNum =getAddScanedNum(hidAndNScanNum[json.csourcebillbid], json.nscannum);
					hidAndNScanNum[json.csourcebillbid] = nScanedNum;
				} else {
					hidAndNScanNum[json.csourcebillbid] = json.nscannum;
				}
				//处理序列号
				if(!NCMMPubUtil.isEmpty(json.vserialcode)||!NCMMPubUtil.isEmpty(json.cspaceid)) {
					var bbitem = {};
					//bbitem["pk_serialcode"] = json.pk_serialcode;
					bbitem["vserialcode"] = json.vserialcode;
					bbitem["nnum"] = json.nscannum;
			        bbitem["nassistnum"]=json.nscanastnum;			        
			        bbitem["clocationid"]=json.cspaceid;
					if(NCMMPubUtil.isEmpty(bbitemJson) || NCMMPubUtil.isEmpty(bbitemJson[itemKey])) {
						bbitemJson[itemKey] = [bbitem];
					} else {
						var newBbitem = bbitemJson[itemKey];
						newBbitem.push(bbitem);
						bbitemJson[itemKey] = newBbitem;
					}
				}			
        }
        }
		}
		if(needCommit == false) {
		    $js.hideLoadingBar();
			$toast("没有选中任何记录！");
			return;
		}
	    var checkResult=DeliveryUtil.checkWhenCommit(itemPKs,scanCount,scanNum);
	    if(!NCMMPubUtil.isEmpty(checkResult)){
	       $js.hideLoadingBar();
	       $alert(checkResult);
	       return;
	    }
		var billinfos = getBillInfos(headKey, headJson, itemKeyJson, itemJson, bbitemJson);
		//测试连接
		NCMMDBUtil.testNCConnection(function(data) {
			if(data == false || data == "false") {
			    $js.hideLoadingBar();
				$toast("连接服务器失败，无法提交！");
				return;
			}
			//$alert("billinfos=" + $jsonToString(billinfos));
			NCMMDBUtil.submitLocaldataToNC("4331_4Csave", billinfos, function(commitInfo) {				
				if(!NCMMPubUtil.isEmpty(commitInfo)) {
				if(commitInfo.return == null || commitInfo.return == "") {
					$js.hideLoadingBar();
					$alert("提交失败：" + $jsonToString(commitInfo));
				} else if(commitInfo["return"].returnFlag == 1) {						
						var billbids = commitInfo.billbids;
						DeliveryUtil.deleteVOsAfterCommit(billbids);
						loadDeliveryScanListData();
						$js.hideLoadingBar();
						$toast("提交成功！");
						}
						else {
						$js.hideLoadingBar();
					$alert("提交失败" + $jsonToString(commitInfo.return.returnDesc));
				}
			} else {
			    $js.hideLoadingBar();
				$alert("提交失败");
			}
			});

		});

	}

	function getAddScanedNum(scanedNum, currentScanedNum) {
		if(scanedNum == null || scanedNum == "") {
			scanedNum += "00.00000";
		} else {
			scanedNum = parseFloat(scanedNum);
		}
		if(currentScanedNum == null || currentScanedNum == "") {
			currentScanedNum += "1.00000";
		} else {
			currentScanedNum = parseFloat(currentScanedNum);
		}
		var newScanedNum = parseFloat(scanedNum).add(parseFloat(currentScanedNum));
		return newScanedNum;
	}
    function convertVOtoBillInfo(scanPK){
        for(var i=0;i<scanPK.length;i++){
        }
    }
	function getBillInfos(headKey, headJson, itemKeyJson, itemJson, bbitemJson) {
		var billinfos = [];
		for(var i = 0; i < headKey.length; i++) {
			var head = headJson[headKey[i]];
			var itemkeys = itemKeyJson[headKey[i]];
			var items = getItems(itemkeys, itemJson, bbitemJson);
			var billinfo = {
				"head": head,
				"items": items
			};
			billinfos.push({
				"billinfo": billinfo
			});
		}
		return billinfos;
	}

	function getItems(itemkeys, itemJson, bbitemJson) {
		var items = [];
		for(var i = 0; i < itemkeys.length; i++) {
			var item = itemJson[itemkeys[i]];
			if(!NCMMPubUtil.isEmpty(bbitemJson) && !NCMMPubUtil.isEmpty(bbitemJson[itemkeys[i]])) {
				//处理bbitem
				var bbitemArr = bbitemJson[itemkeys[i]];
				var bbitems = getBbitems(bbitemArr);
				item["bbitems"] = bbitems;
			}
			items.push({
				"item": item
			});
		}
		return items;
	}

	function getBbitems(bbitemArr) {
		var bbitems = [];
		for(var i = 0; i < bbitemArr.length; i++) {
			var bbitem = {
				"bbitem": bbitemArr[i]
			};
			bbitems.push(bbitem);
		}
		return bbitems;
	}

	function com$yonyou$ncmm_pac_pda$OutForSOScanListController$showMenu(sender, args) {
		NCMMPubMenu.openDropDownList("btn_menu");
	}

	function com$yonyou$ncmm_pac_pda$OutForSOScanListController$search(sender, args) {
		NCMMPubUtil.quickFilter();
	}

function com$yonyou$ncmm_pac_pda$OutForSOScanListController$onresume(sender, args){
    loadDeliveryScanListData();
}
var popDialogInfo = {
		"viewid" : "panel_btn", //显示的控件的id，通常是一个容器控件div
		"popgravity" : "popbottom", //popcenter|poptop|popbottom|popleft|popright,弹出后最终显示的位置
		// istouch : 'false'
	};
	function com$yonyou$ncmm_pac_pda$OutForSOScanListController$doEdit(sender,args){
	$view.closePop(popDialogInfo);
	var row = $id("soutscanlistview").get("row");
		//row = $stringToJSON(row);
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.OutForSOScan", //目标页面（首字母大写）全名
			"isKeep": "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
			"row": row
		});
	}
function	com$yonyou$ncmm_pac_pda$OutForSOScanListController$itemCancel(sender,args){
$view.closePop(popDialogInfo);
}
function com$yonyou$ncmm_pac_pda$OutForSOScanListController$close(sender, args){
$view.close();
}
function com$yonyou$ncmm_pac_pda$OutForSOScanListController$showItemButton(sender, args){
 //$view.openPop(popDialogInfo);
    var row = {};
        row = $id("soutscanlistview").get("row");
        row = $stringToJSON(row);
        if(row && row["row"])
            return;
        $view.openPop(popDialogInfo);

}	com.yonyou.ncmm_pac_pda.OutForSOScanListController.prototype = {

    showDetail : com$yonyou$ncmm_pac_pda$OutForSOScanListController$showDetail,
    doEdit : com$yonyou$ncmm_pac_pda$OutForSOScanListController$doEdit,
    itemDelete : com$yonyou$ncmm_pac_pda$OutForSOScanListController$itemDelete,
    itemCancel : com$yonyou$ncmm_pac_pda$OutForSOScanListController$itemCancel,
    showItemButton : com$yonyou$ncmm_pac_pda$OutForSOScanListController$showItemButton,
    close : com$yonyou$ncmm_pac_pda$OutForSOScanListController$close,
    onresume : com$yonyou$ncmm_pac_pda$OutForSOScanListController$onresume,
		search: com$yonyou$ncmm_pac_pda$OutForSOScanListController$search,
		showMenu: com$yonyou$ncmm_pac_pda$OutForSOScanListController$showMenu,
		doCommit: com$yonyou$ncmm_pac_pda$OutForSOScanListController$doCommit,
		doChecked: com$yonyou$ncmm_pac_pda$OutForSOScanListController$doChecked,
		doAllChecked: com$yonyou$ncmm_pac_pda$OutForSOScanListController$doAllChecked,
		loadScanList: com$yonyou$ncmm_pac_pda$OutForSOScanListController$loadScanList,
		initialize: com$yonyou$ncmm_pac_pda$OutForSOScanListController$initialize,
		evaljs: com$yonyou$ncmm_pac_pda$OutForSOScanListController$evaljs
	};
	com.yonyou.ncmm_pac_pda.OutForSOScanListController.registerClass('com.yonyou.ncmm_pac_pda.OutForSOScanListController', UMP.UI.Mvc.Controller);
} catch(e) {
	$e(e);
}